package uniquindio.app.servicios;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;

public class MainActivity extends Activity {

	private BinderService binderService;

	private ServiceConnectionForBinder sForBinder = new ServiceConnectionForBinder(
			this);

	private Messenger messenger;
	private ServiceConnectionForMessenger sForMessenger = new ServiceConnectionForMessenger(
			this);

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	@Override
	protected void onStart() {
		super.onStart();

		Intent intent = new Intent(this, BinderService.class);
		bindService(intent, sForBinder, BIND_AUTO_CREATE);

		Intent intent2 = new Intent(this, MessengerService.class);
		bindService(intent2, sForMessenger, BIND_AUTO_CREATE);
	}

	@Override
	protected void onStop() {
		super.onStop();

		try {
			unbindService(sForBinder);
		} catch (Exception e) {
			e.printStackTrace();
			Log.e("ServicesExamples", "No se puede desligar el servicio.");
		}
	}

	// ----------- Iniciado -----------------

	/**
	 * Por medio de un servicio de tipo iniciado y con la utilidad de
	 * {@link IntentService}.
	 */
	public void onClickLoadTweets(View view) {
		Log.i("ServicesExamples", "Desde el Hilo principal");

		Intent intent = new Intent(this, StartedService.class);
		startService(intent);
	}

	/**
	 * Por medio de un servicio de tipo ligado y con la utilidad de
	 * {@link Binder}.
	 */
	public void onClickLoadTweetsBinder(View view) {
		Log.i("ServicesExamples", "Desde el Hilo principal");

		if (binderService != null) {
			binderService.consumeTweetsAndCreateNotification();
		}
	}

	public void onClickLoadTweetsMessenger(View view) {
		Log.i("ServicesExamples", "Desde el Hilo principal");

		if (messenger != null) {
			Message message = Message.obtain(null,
					MessengerService.CONSUME_TWEETS_AND_NOTIFICATE, 0, 0);
			try {
				// El mensaje es enviado.
				messenger.send(message);
			} catch (RemoteException e) {
				e.printStackTrace();
			}
		}
	}

	public void setBinderService(BinderService binderService) {
		this.binderService = binderService;
	}

	public void setMessenger(Messenger messenger) {
		this.messenger = messenger;
	}
}
